package com.ai.sml.util;

import java.util.HashSet;
import java.util.Set;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;
import com.ai.sml.util.Constants.SYSTEM_PROP_CONFIG;
/**
 *JedisSingleUtil
 */
public class JedisSingleUtil {
	private static Set<String> jedisNodes = new HashSet<>();
	private volatile static JedisPool pool = null;
	private static final Logger LOGGER = LoggerFactory.getUtilLog(JedisSingleUtil.class);
	
	private JedisSingleUtil(){}
	
	/**
	 * 获取Jedis对象
	 * @return
	 * @throws Exception
	 */
	public static Jedis getJedis() throws MyOwnRuntimeException {
		if (pool == null) {
			synchronized (JedisSingleUtil.class) {
				if(pool==null)
				{
				JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		        jedisPoolConfig.setMaxTotal(10);
//		        jedisPoolConfig.setMaxIdle(PropertiesUtil.getInt(SYSTEM_PROP_CONFIG.REDIS_MAX_IDLE));
//				jedisPoolConfig.setMinIdle(PropertiesUtil.getInt(SYSTEM_PROP_CONFIG.REDIS_MIN_IDLE));
		        pool = new JedisPool(jedisPoolConfig, "127.0.0.1",6379);
			}
			}
		}
		return pool.getResource();
	}
	
	
	/**
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Set<String> getHostNodes() throws MyOwnRuntimeException {
		LOGGER.info("getHostNodes","初始化RedisNodes");
		if (!jedisNodes.isEmpty()) {
			return jedisNodes;
		}
		String redisAddrCfg = PropertiesUtil.getString(SYSTEM_PROP_CONFIG.REDIS_ADDR_CFG);
		if (StringUtil.isEmpty(redisAddrCfg) || redisAddrCfg.split(SYSTEM_PROP_CONFIG.REDIS_CFG_SPLIT).length == 0) {
			throw new MyOwnRuntimeException("System.properties中REDIS_SINGLE_ADDR属性为空");
		}
		String[] addrs = redisAddrCfg.split(SYSTEM_PROP_CONFIG.REDIS_CFG_SPLIT);
		for (String addr : addrs) {
			String regex="((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))):(\\d+)";
			if(!addr.matches(regex)){
				throw new MyOwnRuntimeException("System.properties中REDIS_SINGLE_ADDR属性配置错误");
			}
			jedisNodes.add(addr);
		}
		
		return jedisNodes;
	}
	
}
